/* $RCSFile: PageSettingsDictionary.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/Configuration/Settings/PageSettingsDictionary.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:27  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Settings;

using Path2     =   AddonNice.Settings.Path;
using Cache2    =   AddonNice.Settings.Cache.CurrentCache;
using Key2      =   AddonNice.Settings.Cache.Key;

namespace AddonNice.Configuration
{

    /// <summary>
    /// Dedicated dictionary for module settings
    /// </summary>
    public class PageSettingsDictionary : SettingsDictionary
    {

		#region This delegate is created to manage PagesSettings  Extensions added by pakages
		public static event PageSettingsCreatedEventHandler PageSettingsCreatedEvent;

		public void OnPageSettingsCreated(PageSettingsCreatedEventArgs e) 
		{
			if ( PageSettingsCreatedEvent != null )
				PageSettingsCreatedEvent(e);
		}
		#endregion


        #region overrides from SettingsDictionary
        
        public override void AddUpper(string key, SettingItem value)
        {
            if ( value.Type == SettingsType.Unknown )
                value.Type  =    SettingsType.Page;
            Add(key.ToUpper(), value);
        }

        /// <summary>
        /// Uses the SettingItem.Key as key
        /// Force SettingItem.Type to Page if Unknown
        /// </summary>
        public override void AddSetting(SettingItem value)
        {
            if ( value.Type == SettingsType.Unknown )
                value.Type  =    SettingsType.Page;
            Add(value.Key, value);
        }

        #endregion overrides from SettingsDictionary
        /// <summary>
        /// The PageSettings.GetPageCustomSettings Method returns a SettingsDictionary  of
        /// custom Page specific settings from the database. This method is used by Portals to access misc Page settings.
        /// </summary>
        /// <param name="pageID"></param>
        /// <returns></returns>
        public PageSettingsDictionary GetPageCustomSettings(int wpageID)
        {
            string cachekey             =   Key2.TabSettings(wpageID);
            List<SettingItem> ApplyLst  =   CreateDependencyList();
            if (Cache2.Exists(cachekey))
            {
                if (SettingsTraceSwitch.Sw.TraceVerbose)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PageSettingsDictionary GetPageCustomSettings BEG found in cache pageID: {0}", wpageID), SettingsTraceSwitch.Sw.Info);
                PageSettingsDictionary result = (PageSettingsDictionary)Cache2.Get(cachekey);
                for (int i = 0; i < ApplyLst.Count; i++)
                {
                    SettingItem st  =   ApplyLst[i];
                    st.Type         =   SettingsType.Page;
                    st.ParentDBId   =   wpageID;
                    if (result.ContainsKey(st.Key))
                    {
                        st.SetValueFromDB(result[st.Key].Value);
                        if (SettingsTraceSwitch.Sw.TraceVerbose)
                            Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PageSettingsDictionary GetPageCustomSettings key: {0} initialized.", st.Key), SettingsTraceSwitch.Sw.Info);
                    }
                }
                Status              =   SettingsStatus.Loaded;
                // swap objects in cache 
                Cache2.Remove(cachekey);
                CacheDependency dep = new CacheDependency(PortalSettings.webConfigPath);
                Cache2.Insert(cachekey, this, dep);
                return this;
            }
            if (SettingsTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PageSettingsDictionary GetPageCustomSettings BEG reading from DB pageID: {0}", wpageID), SettingsTraceSwitch.Sw.Info);
            PagesDB PageDB      =   new PagesDB();
            Dictionary<string, string> valDic = new Dictionary<string, string>();
            SqlDataReader dr    =   null;
            try
            {
                dr              =   PageDB.GetPageCustomSettings(wpageID);
                while (dr.Read())
                {
                    string key  =   (string)dr[StStr.DBSettingName];
                    // empty or null keys not allowed
                    if (string.IsNullOrEmpty(key))
                        continue;
                    // nul content not allowed but string.empty allowed
                    object ob   =   dr[StStr.DBSettingValue];
                    if (ob == DBNull.Value)
                        continue;
                    string val  =   ob.ToString();
                    // 2/12/07 if (string.IsNullOrEmpty(val))
                    //    continue;
                    string k    =   key.ToUpper();
                    if (ContainsKey(k) &&
                        !val.Equals(this[k].Value))
                    {
                        if (SettingsTraceSwitch.Sw.TraceVerbose)
                            Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PageSettingsDictionary GetPageCustomSettings pageID: {0}, key: {1}, val: {2}, old val:{3}", new object[] { wpageID, k, val, this[k].Value }), SettingsTraceSwitch.Sw.Info);
                        this[k].Key = k;
                        valDic.Add(k, val);
                    }
                }
                if (SettingsTraceSwitch.Sw.TraceVerbose)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PageSettingsDictionary GetPageCustomSettings Inserting in cache pageID: {0}", wpageID), SettingsTraceSwitch.Sw.Info);
                CacheDependency dep = new CacheDependency(PortalSettings.webConfigPath);
                Cache2.Insert(cachekey, this, dep);
                // if any, apply changes in order: items with dependencies fisrt
                if (valDic.Count > 0)
                {
                    for (int i = 0; i < ApplyLst.Count; i++)
                    {
                        SettingItem st = ApplyLst[i];
                        if (valDic.ContainsKey(st.Key))
                        {
                            st.SetValueFromDB(valDic[st.Key]);
                        }
                    }
                }
                Status          =   SettingsStatus.Loaded;
            }
            catch (Exception exp)
            {
                if (SettingsTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PageSettingsDictionary GetPageCustomSettings pageID: {0}, ex : {1}", wpageID, exp), SettingsTraceSwitch.Sw.Info);
                throw;
            }
            finally
            {
                if (dr != null)
                    dr.Close();
            }
            if (SettingsTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PageSettingsDictionary GetPageCustomSettings END pageID: {0}, count:{1}", wpageID, Count), SettingsTraceSwitch.Sw.Info);
            return this;
        }
    }

}
